package com.infoland.afanmall.model.fuPin.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.infoland.afanmall.R;
import com.infoland.afanmall.base.fragment.BaseLazyFragment;
import com.infoland.afanmall.base.util.CONST;
import com.infoland.afanmall.base.util.LogKit;
import com.infoland.afanmall.base.util.StatusBarKit;
import com.infoland.afanmall.base.util.ToolsKit;
import com.infoland.afanmall.base.util.layoutManager.GridSpacingItemDecoration;
import com.infoland.afanmall.base.util.okhttp.OkHttpKit;
import com.infoland.afanmall.base.view.viewPagerCards2.CardPagerAdapter;
import com.infoland.afanmall.base.view.viewPagerCards2.ShadowTransformer;
import com.infoland.afanmall.model.fuPin.activity.FpCityListActivity;
import com.infoland.afanmall.model.fuPin.activity.FpCunInfoActivity;
import com.infoland.afanmall.model.fuPin.activity.FpCunListActivity;
import com.infoland.afanmall.model.fuPin.adapter.FpCunZiAdapter;
import com.infoland.afanmall.model.fuPin.adapter.FpGoodsAdapter;
import com.infoland.afanmall.model.fuPin.entity.FuPinCunResponse;
import com.infoland.afanmall.model.fuPin.entity.FuPinGoodsResponse;
import com.infoland.afanmall.model.fuPin.entity.FuPinGuanPageResponse;
import com.infoland.afanmall.model.youXuan.activity.GoodInfoActivity;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.wang.avi.AVLoadingIndicatorView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;


public class FuPinFragment extends BaseLazyFragment {
    Unbinder unbinder;

    @BindView(R.id.fu_pin_title)
    LinearLayout fuPinTitle;
    @BindView(R.id.fu_pin_title_layout)
    LinearLayout fuPinTitleLayout;
    @BindView(R.id.fu_pin_recy_cun)
    RecyclerView fuPinRecyCun;
    @BindView(R.id.fu_pin_recy_goods)
    RecyclerView fuPinRecyGoods;

    @BindView(R.id.fu_pin_refresh)
    RefreshLayout fuPinRefresh;
    FpCunZiAdapter cunZiAdapter;
    FpGoodsAdapter goodsAdapter;
    @BindView(R.id.avi_pt)
    AVLoadingIndicatorView aviPt;
    @BindView(R.id.fu_pin_data_viewpager)
    ViewPager viewPager;
    @BindView(R.id.fu_pin_txt4)
    TextView fuPinTxt4;
    @BindView(R.id.fu_pin_txt1)
    TextView fuPinTxt1;
    @BindView(R.id.fu_pin_txt2)
    TextView fuPinTxt2;
    @BindView(R.id.fu_pin_txt_layout)
    LinearLayout fuPinTxtLayout;

    List<Integer> city_ids;
    boolean lastPAge = false;
    int pageNumber = 1;
    int fupinguanId = 0;
    private CardPagerAdapter mCardAdapter;
    private ShadowTransformer mCardShadowTransformer;

    public int getLayout() {
        return R.layout.fu_pin_fragment;
    }

    //入口
    @Override
    public void initData() {
        //
        StatusBarKit.setPaddingSmart(getActivity(), fuPinTitleLayout);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2);
        fuPinRecyGoods.setLayoutManager(gridLayoutManager);
        fuPinRecyGoods.addItemDecoration(new GridSpacingItemDecoration(
                2, SizeUtils.dp2px(10),
                true));
        //
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        fuPinRecyCun.setLayoutManager(linearLayoutManager);

        city_ids = new ArrayList<>();
        /*** 加载更多**/
        fuPinRefresh.setOnLoadMoreListener(refreshLayout -> {
            refLoadStart();
            loadGoods();
        });
        /*** 刷新**/
        fuPinRefresh.setOnRefreshListener(refreshLayout -> {
            fuPinRefresh.setEnableRefresh(false);
            fuPinRefresh.setEnableLoadMore(false);
            refGoods();
        });
        /*** 更多扶贫村**/
        fuPinTxt4.setOnClickListener(v -> {
            ToolsKit.setSleep2000(fuPinTxt4);
            Bundle bundle = new Bundle();
            bundle.putInt("fupinguanId", fupinguanId);
            ToolsKit.go(FpCunListActivity.class, bundle);
        });
        /*** 更多扶贫省**/
        fuPinTxtLayout.setOnClickListener(v -> {
            ToolsKit.setSleep2000(fuPinTxtLayout);
            Intent Intent = new Intent(getActivity(), FpCityListActivity.class);
            startActivityForResult(Intent, CONST.RESULT_CODE_TO_FU_PIN_CITY);
        });
        refLoadStart();
        getBanner();
        LogKit.E("initData ---->   ", " initData ");

    }

    //加载**/
    private void loadGoods() {
        JSONObject jsonObject = new JSONObject();
        if (getPage()) {
            jsonObject.put("pageNumber", this.pageNumber + "");
            jsonObject.put("pageSize", CONST.FU_PIN_GOOD_SIZE + "");
            jsonObject.put("fupinguanId", fupinguanId + "");

            new OkHttpKit().send(
                    response200 -> {
                        LogKit.E("loadGoods ---->   ", "  " + response200);
                        FuPinGoodsResponse fuPinGoodsResponse = JSONObject.parseObject(response200, FuPinGoodsResponse.class);
                        FuPinGoodsResponse.ObjectBean object = fuPinGoodsResponse.getObject();
                        if (object.getTotalRow() > 0) {
                            setPage(object.getPageNumber(), object.isLastPage());
                        }
                        List<FuPinGoodsResponse.ObjectBean.ListBean> list = object.getList();
                        if (goodsAdapter != null && list != null) {
                            goodsAdapter.addData(list);
                        }
                        refLoadOk();
                    },
                    error -> {
                        refLoadError();
                    }
            ).post(CONST.FU_PIN_GUAN_GOODS, jsonObject, getActivity());
        }

    }

    //刷新**/
    private void refGoods() {
        initPage();
        getBanner();
    }

    //查询轮播**/
    private void getBanner() {

        new OkHttpKit().send(
                response200 -> {
                    LogKit.E("查询轮播 ---->   ", "  " + response200);
                    setFuPinBanner(JSONObject.parseObject(response200, FuPinGuanPageResponse.class));
                    refLoadOk();
                },
                error -> {
                    refLoadError();

                }
        ).post(CONST.FU_PIN_GUAN, new JSONObject(), getActivity());
    }

    //询村子**/
    private void getCunZi(int fupinguanId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pageNumber", 1);
        jsonObject.put("pageSize", CONST.FU_PIN_CUN_ZI_SIZE);
        jsonObject.put("fupinguanId", fupinguanId);
        new OkHttpKit().send(
                response200 -> {
                    LogKit.E("查询村子 ---->   ", "  " + response200);
                    getGoods(this.fupinguanId);
                    FuPinCunResponse fuPinCunResponse = JSONObject.parseObject(response200, FuPinCunResponse.class);
                    setFuPinCunZi(fuPinCunResponse);

                },
                error -> {
                    refLoadError();

                }
        ).post(CONST.FU_PIN_CUN, jsonObject, getActivity());
    }

    //查询扶贫管商品**/
    private void getGoods(int fupinguanId) {
        JSONObject jsonObject = new JSONObject();
        if (getPage()) {
            jsonObject.put("pageNumber", this.pageNumber + "");
            jsonObject.put("pageSize", CONST.FU_PIN_GOOD_SIZE + "");
            jsonObject.put("fupinguanId", fupinguanId + "");

            new OkHttpKit().send(
                    response200 -> {
                        LogKit.E("查询扶贫管商品 ---->   ", "  " + response200);
                        FuPinGoodsResponse fuPinGoodsResponse = JSONObject.parseObject(response200, FuPinGoodsResponse.class);
                        setFuPinGoods(fuPinGoodsResponse);
                        refLoadOk();
                    },
                    error -> {
                        refLoadError();

                    }
            ).post(CONST.FU_PIN_GUAN_GOODS, jsonObject, getActivity());
        }
    }

    //设置扶贫管轮播图**/
    private void setFuPinBanner(FuPinGuanPageResponse fuPinGuanPageResponse) {
        city_ids.clear();
        mCardAdapter = new CardPagerAdapter();
        for (FuPinGuanPageResponse.ObjectBean o : fuPinGuanPageResponse.getObject()) {
            city_ids.add(o.getId());
            mCardAdapter.addCardItem(o.getPromotion_image_url());
        }
        mCardShadowTransformer = new ShadowTransformer(viewPager, mCardAdapter);
        viewPager.setAdapter(mCardAdapter);
        viewPager.setPageTransformer(false, mCardShadowTransformer);
        viewPager.setOffscreenPageLimit(3);
        mCardShadowTransformer.enableScaling(true); //放大
        /*** 切换TAB查询**/
        mCardShadowTransformer.setPageSelectLinster(postion -> {
            initPage();
            refLoadStart();
            FuPinGuanPageResponse.ObjectBean objectBean = fuPinGuanPageResponse.getObject().get(postion);
            fupinguanId = objectBean.getId();
            fuPinTxt1.setText(objectBean.getProvince_name());
            getCunZi(fupinguanId);
        });
        /*** 初始查询**/
        if (fuPinGuanPageResponse.getObject().size() > 0) {
            viewPager.setCurrentItem(0);
            String province_name = fuPinGuanPageResponse.getObject().get(0).getProvince_name();
            fuPinTxt1.setText(province_name);
            fupinguanId = fuPinGuanPageResponse.getObject().get(0).getId();
            initPage();
            getCunZi(fupinguanId);
        }
    }

    // 设置扶贫商品**/
    private void setFuPinGoods(FuPinGoodsResponse fuPinGoodsResponse) {
        if (fuPinGoodsResponse.isSuccess()) {
            FuPinGoodsResponse.ObjectBean object = fuPinGoodsResponse.getObject();
            if (object.getTotalRow() > 0) {
                setPage(object.getPageNumber(), object.isLastPage());
            } else {
                setPage(1, true);
            }
            goodsAdapter = new FpGoodsAdapter(R.layout.fu_pin_good_item, object.getList());
            goodsAdapter.setOnItemClickListener((adapter, view, position) -> {
                FuPinGoodsResponse.ObjectBean.ListBean o =
                        (FuPinGoodsResponse.ObjectBean.ListBean) adapter.getData().get(position);
                Bundle b = new Bundle();
                b.putInt("id", o.getId());
                /*** 去品详情页**/
                ToolsKit.go(GoodInfoActivity.class, b);
            });
            fuPinRecyGoods.setAdapter(goodsAdapter);
        } else {
            ToastUtils.showShort("暂时没有商品信息");
            ArrayList<FuPinGoodsResponse.ObjectBean.ListBean> objects = new ArrayList<>();
            goodsAdapter = new FpGoodsAdapter(R.layout.fu_pin_good_item, objects);
            fuPinRecyGoods.setAdapter(goodsAdapter);
            setPage(1, false);
        }
    }

    //设置扶贫村子**/
    private void setFuPinCunZi(FuPinCunResponse fuPinCunResponse) {
        if (fuPinCunResponse.isSuccess()) {
            cunZiAdapter = new FpCunZiAdapter(R.layout.fu_pin_cun_item, fuPinCunResponse.getObject().getList());
            cunZiAdapter.setOnItemClickListener((adapter, view, position) -> {
                FuPinCunResponse.ObjectBean.ListBean o =
                        (FuPinCunResponse.ObjectBean.ListBean) adapter.getData().get(position);
                Bundle bundle = new Bundle();
                bundle.putInt("fupincunId", o.getId());
                ToolsKit.go(FpCunInfoActivity.class, bundle);
            });
            fuPinRecyCun.setAdapter(cunZiAdapter);
        } else {
            ToastUtils.showShort("暂时没有村子信息");
            ArrayList<FuPinCunResponse.ObjectBean.ListBean> objects = new ArrayList<>();
            cunZiAdapter = new FpCunZiAdapter(R.layout.fu_pin_cun_item, objects);
            fuPinRecyCun.setAdapter(cunZiAdapter);
        }
    }

    private void initPage() {
        this.pageNumber = 1;
        this.lastPAge = false;
    }

    private void setPage(int pageNumber, boolean lastPAge) {
        this.pageNumber = (pageNumber + 1);
        this.lastPAge = lastPAge;
    }

    private boolean getPage() {
        if (lastPAge) {
            fuPinRefresh.setEnableLoadMore(false);
            fuPinRefresh.setEnableRefresh(true);
            fuPinRefresh.finishLoadMore();
            fuPinRefresh.finishRefresh();
            aviPt.setVisibility(View.GONE);
            ToastUtils.showShort("已经是最后一页");
            return false;
        } else {
            return true;
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(getLayout(), container, false);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    //    /*** 加载或刷新失败**/
    private void refLoadError() {
        fuPinRefresh.setEnableRefresh(true);
        fuPinRefresh.setEnableLoadMore(true);
        fuPinRefresh.finishRefresh(500);
        fuPinRefresh.finishLoadMore();
        aviPt.setVisibility(View.GONE);
    }

    //    /*** 加载或刷新完成**/
    private void refLoadOk() {
        fuPinRefresh.setEnableRefresh(true);
        fuPinRefresh.setEnableLoadMore(true);
        fuPinRefresh.finishRefresh(500);
        fuPinRefresh.finishLoadMore();
        aviPt.setVisibility(View.GONE);
    }

    //    /*** 加载或刷新开始**/
    private void refLoadStart() {
        fuPinRefresh.setEnableRefresh(false);
        fuPinRefresh.setEnableLoadMore(false);
        aviPt.setVisibility(View.VISIBLE);
    }

    //    /*** 接收返回的ID**/
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogKit.E("FuPinFragment  requestCode ---> ", "  " + requestCode);
        LogKit.E("FuPinFragment  resultCode  ---> ", "  " + resultCode);
        LogKit.E("FuPinFragment data   ---> ", "  " + data);
        if (resultCode == CONST.RESULT_CODE_TO_FU_PIN_CITY) {
            Bundle extras = data.getExtras();
            if (extras != null) {
                int city_id = extras.getInt("city_id");
                for (int i = 0; i < city_ids.size(); i++) {
                    if (city_id == city_ids.get(i)) {
                        viewPager.setCurrentItem(i);
                        fuPinTxt1.setText(extras.getString("city_name"));
                        fupinguanId = city_id;
//                        refLoadStart();
//                        getCunZi(fupinguanId);
                    }
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        ToolsKit.deleteOKHttp(getActivity());
        super.onDestroy();
    }
}
